require("common")
require("task")
require("handler")

gui = {
	new = function(nwins)
		assert((type(nwins) == "number") or (nwins == nil), "nwins must be a number or nil")
		if nwins == nil then nwins = 1 end
		local self = {}
		self.windows = {}
		self.commonHandler = handler.new(self)
		self.handler = handler.new(self)
		self.commonHandler:add("*", function(gui, id, command, ...)
			self.handler:dispatch(command, ...)
		end)
		for i = 1, nwins do
			local window = {
				gui = self,
				
				id = i - 1,
				
				send = function(self, format, ...)
					self.gui.task:sendln(string.format("%d %s", self.id, string.format(format, ...)))
				end,
				
				open = function(self, url)
					self:send("open %s", url)
				end,
				
				back = function(self, url)
					self:send("back")
				end,
				
				forward = function(self, url)
					self:send("forward")
				end,
				
				clearHistory = function(self, count)
					if count == nil then count = 0 end
					self:send("clearhistory %d", count)
				end,
				
				size = function(self, width, height)
					self:send("size %d %d", width, height)
				end,
				
				position = function(self, x, y)
					self:send("position %d %d", x, y)
				end,
				
				visible = function(self, on)
					self:send("visible %s", tostring(on))
				end,
				
				zindex = function(self, arg)
					self:send("zindex %s", arg)
				end,
				
				scroll = function(self, on)
					self:send("scroll %s", tostring(on == true))
				end,
				
				exec = function(self, script)
					self:send("exec %s", script)
				end,
				
				clear = function(self)
					self:open("about:blank")
				end
			}
			window.handler = handler.new(window)
			self.commonHandler:add(tostring(i - 1), function(window, id, command, ...)
				self.windows[i].handler:dispatch(command, ...)
			end)
			table.insert(self.windows, window)
		end
		self.task = task.executep(common.getConfig("path.webgui"), "-" .. nwins)
		setmetatable(self, { __index = gui })
		return self
	end,

	send = function(self, format, ...)
		self.task:sendln(string.format(format, ...))
	end,
	
	timer = function(self, ms)
		self:send("timer %d", ms)
	end,
	
	loop = function(self)
		self.task:loop(function(task, line)
			local id, command, arg = (line:gmatch("([^ ]+) ([^ ]+) ?(.*)"))()
			if id then
				self.commonHandler:dispatch(id, command, arg)
			else
				log("gui", "Unparseable line: %q", line)
			end
		end)
	end,
				
	exit = function(self)
		self:send("exit")
	end
}


